package com.whl215.kit.adapter.element

import android.os.Handler
import android.os.Looper
import android.os.Message
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.viewbinding.ViewBinding
import com.whl215.kit.adapter.GrapeBaseAdapter
import com.whl215.kit.adapter.GrapeViewHolder
import com.whl215.kit.adapter.R
import com.whl215.kit.adapter.databinding.GrapeItemElementLoadMoreBinding

/**
 * author： happiness
 * date： 2021/4/15
 * description：
 */
class LoadMoreGrapeElement : GrapeElement() {
    companion object {
        private const val FLAG = 0
    }

    var ableLoadMore = false
    var onLoadMoreListener: OnLoadMoreListener? = null
        set(value) {
            ableLoadMore = true
            field = value
        }
    private val handler = Handler(Looper.getMainLooper(), object : Handler.Callback {
        override fun handleMessage(msg: Message): Boolean {
            onLoadMoreListener?.onLoadMore()
            return true
        }

    })

    override fun getViewBinding(parent: ViewGroup): ViewBinding {
        return GrapeItemElementLoadMoreBinding
            .inflate(LayoutInflater.from(parent.context),parent,false)
    }

    override fun bindViewHolder(holder: GrapeViewHolder, action: GrapeAction) {
        val viewBinding:GrapeItemElementLoadMoreBinding = holder.getViewBinding()
        viewBinding.itemElementProgressBar.visibility =
            if (action.code == GrapeAction.LOAD_MORE_BEGIN) View.VISIBLE else View.GONE
        viewBinding.itemElementTvMessage .text = action.message
    }

    fun loadMore() {
        if (!handler.hasMessages(FLAG)) {
            handler.sendEmptyMessage(FLAG)
        }
    }

    /**
     * 加载更多监听
     */
    interface OnLoadMoreListener {
        fun onLoadMore()
    }

}